import { LOGIN_TYPE, USER_KEY } from '@src/const';
import Cookies from 'js-cookie';
import { decrypt, encrypt } from './security';
import dayjs from 'dayjs';
import login from '@src/apis/login';
import { IUser } from '@src/types/account';

export interface IUserKey {
  expires: dayjs.Dayjs;
  userId: string;
}

// 自动登录
export const autoLogin = (userKey: string): Promise<IUser> => {
  if (!userKey) {
    return null as unknown as Promise<IUser>;
  }

  // 自动登录
  return login(LOGIN_TYPE.AUTO_LOGIN, {
    userKey,
  });
};

// 更新用户的userId
export const updateUserCookies = (userId: string, expires = 7) => {
  // 七天内免登录
  Cookies.set(
    USER_KEY,
    encrypt(
      JSON.stringify({
        expires: dayjs().add(expires, 'day'),
        userId,
      }),
    ),
    { expires },
  );
};

// 移除key
export const deleteUserCookies = () => {
  Cookies.remove(USER_KEY);
};

// 获取用户cookies
export const getUserCookies = (): string => {
  const userKey = Cookies.get(USER_KEY) || '';
  if (!userKey) {
    return '';
  }

  const { expires } = JSON.parse(decrypt(userKey)) as IUserKey;

  // cookie过期
  if (dayjs(expires).isBefore(dayjs())) {
    deleteUserCookies();
    return '';
  }

  return userKey;
};
